package com.mockapi.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.StringWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * FreeMarker工具类
 */
@Slf4j
public class FreeMarkerUtil {

    private static final Configuration configuration;

    static  {
        configuration = new Configuration(Configuration.VERSION_2_3_32);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "templates");
    }

    /**
     * 渲染模板
     *
     * @param templateContent 模板内容
     * @param request        请求信息
     * @return 渲染后的内容
     */
    public static String renderTemplate(String templateContent, Map<String, Object> request) {
        try {
            Template template = new Template("template", templateContent, configuration);
            StringWriter writer = new StringWriter();
            
            // 构建数据模型
            Map<String, Object> dataModel = buildDataModel(request);
            
            template.process(dataModel, writer);
            return writer.toString();
        } catch (IOException | TemplateException e) {
            log.error("模板渲染失败", e);
            return templateContent;
        }
    }

    /**
     * 构建数据模型
     *
     * @param request 请求信息
     * @return 数据模型
     */
    private static Map<String, Object> buildDataModel(Map<String, Object> request) {
        Map<String, Object> dataModel = new HashMap<>();
        
        // 请求信息
        dataModel.put("request", request);
        
        // 时间相关
        LocalDateTime now = LocalDateTime.now();
        dataModel.put("now", now);
        dataModel.put("timestamp", System.currentTimeMillis());
        dataModel.put("date", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        dataModel.put("time", now.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        dataModel.put("datetime", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        
        // 随机数
        dataModel.put("random", new RandomFunc());
        
        // 环境变量
        dataModel.put("env", System.getenv());
        
        return dataModel;
    }

    /**
     * 随机数工具类
     */
    public static class RandomFunc {
        
        private final Random random = new Random();
        
        /**
         * 生成随机整数
         */
        public int nextInt() {
            return random.nextInt();
        }
        
        /**
         * 生成指定范围的随机整数
         */
        public int nextInt(int bound) {
            return random.nextInt(bound);
        }
        
        /**
         * 生成随机长整数
         */
        public long nextLong() {
            return random.nextLong();
        }
        
        /**
         * 生成随机双精度浮点数
         */
        public double nextDouble() {
            return random.nextDouble();
        }
        
        /**
         * 生成随机布尔值
         */
        public boolean nextBoolean() {
            return random.nextBoolean();
        }
        
        /**
         * 生成指定长度的随机字符串
         */
        public String nextString(int length) {
            String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++) {
                sb.append(chars.charAt(random.nextInt(chars.length())));
            }
            return sb.toString();
        }
        
        /**
         * 生成UUID
         */
        public String uuid() {
            return java.util.UUID.randomUUID().toString();
        }
    }
} 